#include "config.h"

#include "dushd.h"

static const char **
build_argv_arr(sr_t *sr_args)
{
	char	const **argv_arr;
	int	num = sr_get_num_child(sr_args), i;

	argv_arr = (char **)ecm_malloc(sizeof(char *) * (num + 3));
	argv_arr[0] = comspec;
	argv_arr[1] = "/C";
	for (i = 0; i < num; i++)
		argv_arr[i + 2] = sr_geti_str(sr_args, i);
	argv_arr[i + 2] = NULL;

	return argv_arr;
}

static sr_t *
read_output(int fd)
{
	////TODO
	return NULL;
}

static sr_t *
dushd_execute(sr_t *sr_args, ecm_uint32 timeout)
{
	ecm_exectx_t	exectx;
	sr_t	*sr_res, *sr_outputs;
	int	fd_in = -1;
	ecm_err_t	err;

	ecm_init_exectx(&exectx);
	exectx.argv_arr = build_argv_arr(sr_args);
	exectx.stderr_enabled = ECM_TRUE;

	sr_res = sr_create_dir();
	sr_outputs = sr_createc_dir(sr_res, "outputs");

	if ((err = ecm_exec_process(&exectx, &fd_in, NULL)) == ECM_OK) {
		sr_t	*sr_out;
		
		sr_out = read_output(fd_in);
		if ((err = ecm_wait_process(&exectx, timeout * 1000)) != ECM_OK) {
			sr_createc_int(sr_res, "exitcode", ST_INT, 127);
		}
		else {
			sr_createc_int(sr_res, "exitcode", ST_INT, exectx.exitcode);
		}
		sr_append(sr_outputs, sr_out);
	}
	else {
		sr_createc_int(sr_res, "exitcode", ST_INT, 127);
		sr_append(sr_outputs, sr_create_oct(ST_OCT, 0, NULL));
	}

	ecm_free(exectx.argv_arr);
	ecm_clear_exectx(&exectx);

	return sr_res;
}

sr_t *
dushd_cb_execute(ecm_ebc_t ebc, ebc_addr_t *saddr, ebc_addr_t *daddr, sr_t *sr_info, ecm_ptr_t ctx)
{
	sr_t	*sr_args = sr_getc(sr_info, "args");
	ecm_uint32	timeout = sr_getc_int(sr_info, "timeout");

	return dushd_execute(sr_args, timeout);
}
